package com.tongfusoft.document.web.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.tongfusoft.spring.web.security.service.impl.SecurityPasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	@Qualifier("documentUserDetailsService")
	private UserDetailsService userDetailsService;

	@Autowired
	@Qualifier("customAuthenticationSuccessHandler")
	private AuthenticationSuccessHandler authenticationSuccessHandler;
	@Autowired
	@Qualifier("securityPasswordEncoder")
	private PasswordEncoder passwordEncoder;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
				// 不判断是否登录 start
				.antMatchers("/public/**").permitAll()
				.antMatchers("/**/*.jpg").permitAll()
				.antMatchers("/**/*.png").permitAll()
				.antMatchers("/**/*.js").permitAll()
				.antMatchers("/**/*.css").permitAll()
				.antMatchers("/**/*.woff").permitAll()
				.antMatchers("/**/*.woff2").permitAll()
				.antMatchers("/**/*.html").permitAll()
				.antMatchers("/favicon.ico").permitAll()
				// 不判断是否登录 end

				.anyRequest().fullyAuthenticated().and().formLogin()
				.loginPage("/login")
				.failureUrl("/login?error")
				.usernameParameter("username")
				.successHandler(authenticationSuccessHandler).permitAll().and().logout()
				.logoutUrl("/logout")
				.deleteCookies("remember-me")
				.logoutSuccessUrl("/login").permitAll().and().rememberMe();
		http.csrf().disable();
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
	}
	
	
}
